package test.app.audit.interceptor;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;

import test.app.audit.IAuditLogger;
import test.app.audit.IAuditable;
import test.app.audit.OperationType;
import test.app.audit.RecordType;

public class AuditLogInterceptor extends EmptyInterceptor{
	
	private static final long serialVersionUID = 6878711368770360446L;

	protected Log logger = LogFactory.getLog(getClass());
	
	private IAuditLogger auditLogger;

	
	public boolean onSave(Object entity, Serializable id, Object[]state, String[] propertyNames, Type[] types) {
		
		if(entity instanceof IAuditable) {
			getAuditLogger().addEntityAuditRecord((IAuditable)entity, OperationType.CREATE,RecordType.ENTITYLOG);
		}
		return false;
	}
	
	public void onDelete(Object entity, Serializable id, Object[]state, String[] propertyNames, Type[] types) {
		if(entity instanceof IAuditable) {
			getAuditLogger().addEntityAuditRecord((IAuditable)entity, OperationType.DELETE,RecordType.ENTITYLOG);
		}
	}
	
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
		if(entity instanceof IAuditable) {
			getAuditLogger().addEntityAuditRecord((IAuditable)entity,OperationType.UPDATE,RecordType.ENTITYLOG);
		}
		
		return false;
	}
	

	public void afterTransactionCompletion(Transaction transaction) {
		if(transaction.wasCommitted()) {
			logger.debug("Finalizada la transaccion del Interceptor");
		}
			
	}
	
	/**
	 * @return   Returns the auditLogger.
	 */
	public IAuditLogger getAuditLogger() {
		return auditLogger;
	}
	/**
	 * @param auditLogger   The auditLogger to set.
	 */
	public void setAuditLogger(IAuditLogger auditLogger) {
		this.auditLogger = auditLogger;
	}


}

